from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authtoken.models import Token
from django.contrib.auth import authenticate
from rest_framework_jwt.serializers import User

from login.models import Users
from django.utils import timezone
import logging

from login.serializers import CustomUserSerializer
from .serializers import UserSerializer

logger = logging.getLogger(__name__)


class LoginView(APIView):
    def post(self, request):
        ret = {}

        try:
            # 获取请求体中的数据
            username = request.data.get('username')
            password = request.data.get('password')

            logger.debug(f"Received username: {username}, password: {'*' * len(password)}")  # 隐藏密码
            # 检查用户名和密码是否为空
            if not username or not password:
                ret['code'] = 400
                ret['msg'] = "请求参数有误"
                return Response(ret, status=status.HTTP_200_OK)

            # 验证用户名和密码
            user = authenticate(username=username, password=password)
            if user is not None and user.is_active:
                # 认证成功
                ret['code'] = 200
                ret['msg'] = "登录成功"

                # 获取客户端的真实IP地址
                x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
                if x_forwarded_for:
                    client_ip = x_forwarded_for.split(',')[0]
                else:
                    client_ip = request.META.get('REMOTE_ADDR')

                logger.info(f"User {user.username} logged in from IP: {client_ip}")

                # 更新用户的IP地址和最后登录时间
                user.ip_address = client_ip
                user.last_login = timezone.now()  # 使用Django的timezone模块来确保正确的时间
                user.save(update_fields=['ip_address', 'last_login'])

                # 调试信息
                logger.debug(f"Token model: {Token}")
                logger.debug(f"Token objects: {Token.objects}")

                token, created = Token.objects.get_or_create(user=user)
                ret['data'] = {
                    'username': user.username,
                    'ip_address': client_ip,
                    'last_login': timezone.now(),
                    'token': token.key
                }
            else:
                # 认证失败
                ret['code'] = 400
                ret['msg'] = "用户名或密码错误或用户未激活"
                return Response(ret, status=status.HTTP_200_OK)

        except ValueError as ve:
            if "badly formed hexadecimal UUID string" in str(ve):
                ret['code'] = 400
                ret['msg'] = "无效的UUID格式"
            else:
                ret['code'] = 500
                ret['msg'] = str(ve)
            return Response(ret, status=status.HTTP_200_OK)

        except Exception as e:
            ret['code'] = 500
            ret['msg'] = str(e)
            logger.error(f"An unexpected error occurred: {e}")
            return Response(ret, status=status.HTTP_200_OK)

        return Response(ret, status=status.HTTP_200_OK)

class RegisterView(APIView):
    def post(self, request):
        logger.info(f"Received data: {request.data}")
        serializer = CustomUserSerializer(data=request.data)

        if serializer.is_valid():
            user = serializer.save()
            return Response({'message': '用户已成功创建'}, status=status.HTTP_201_CREATED)
        else:
            logger.error(f"Validation errors: {serializer.errors}")
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class AllUsersView(APIView):
    def get(self, request):
        users = Users.objects.all()  # 获取所有用户
        serializer = UserSerializer(users, many=True)  # 序列化多个对象
        return Response(serializer.data, status=status.HTTP_200_OK)



